//
//  BookmarkViewController.swift
//  HiBook
//
//  Created by Apple on 16/7/27.
//  Copyright © 2016年 Apple. All rights reserved.
//

import UIKit

class MarkViewController: CommonViewController,WKUIDelegate ,WKNavigationDelegate ,WKScriptMessageHandler {

    var markWebView : WKWebView?
    
    var isSuccess : String?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "书评"
        setWebView()
        
        loadWebView()
        self.view.addSubview(markWebView!)
        
        
        self.markWebView?.scrollView.mj_header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(self.doRefresh))
        self.markWebView?.scrollView.mj_header.beginRefreshing()
        
    }
    
    func doRefresh(){
        self.markWebView?.evaluateJavaScript("reload()", completionHandler: { (o, e) in
            print(e)
            print(o)
        })
    }
    
    
    func loadWebView(){
        
        let request = NSURLRequest(URL: NSURL(string: "http://\(MAIN_IP):8080/hibook/markView.do")!)
        
        self.markWebView?.loadRequest(request)
        
    }
    
    func setWebView(){
        
        let config = WKWebViewConfiguration()
        
        self.markWebView = WKWebView(frame: self.view.frame ,configuration: config)
        
        self.markWebView?.UIDelegate = self
        
        self.markWebView?.navigationDelegate = self
        
        self.markWebView?.configuration.userContentController.addScriptMessageHandler(self, name: "responesToPhone")
        
        self.markWebView?.allowsBackForwardNavigationGestures = true
    }
    
    func responesToPhone(){
        print("刷新成功")
        self.markWebView?.scrollView.mj_header.endRefreshing()
        
    }
    
    
    func webViewDidStartLoad(webView: UIWebView) {
        NSLog("启动")
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        NSLog("结束")
    }
    
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        NSLog("error:\(error)")
    }
    
    func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
        
        NSLog("方法名:\(message.name) 传回:\(message.body)")
        
        self.isSuccess = message.body as? String
        
        self.responesToPhone()
        
    }

    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
